package cn.gailvlun.gll.presentation.charge

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.GridLayoutManager
import android.view.View
import cn.gailvlun.gll.BuildConfig
import cn.gailvlun.gll.R
import cn.gailvlun.gll.databinding.ActivityChargeBinding
import cn.gailvlun.gll.databinding.ItemChargeBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.pay.GetBalanceRes
import cn.gailvlun.gll.net.pay.PayMethod
import cn.gailvlun.gll.net.pay.PayReq
import cn.gailvlun.gll.net.pay.PayResult
import cn.gailvlun.gll.pay.UniPay
import cn.gailvlun.gll.pay.UniPayListener
import cn.gailvlun.gll.pay.UniPayMethod
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.base.WebViewActivity
import cn.gailvlun.gll.presentation.charge.adapter.ChargeAdapter
import cn.gailvlun.gll.presentation.charge.model.Outcome
import cn.gailvlun.gll.presentation.charge.model.ProductModel
import cn.gailvlun.gll.presentation.charge.vm.ChargeViewModel
import cn.gailvlun.gll.util.*

class ChargeActivity : BaseActivity() {

    companion object {
        fun openActivity(context: Context) {
            context.startActivity(Intent(context, ChargeActivity::class.java))
        }
    }

    private lateinit var mBinding: ActivityChargeBinding
    private var mViewModel: ChargeViewModel? = null
    private var mAdapter: ChargeAdapter? = null
    private var mLayoutManager: GridLayoutManager? = null

    override fun initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_charge)
        mViewModel = ViewModelProviders.of(this).get(ChargeViewModel::class.java)

        initProducts()
        selectProduct(0)
    }

    private fun initProducts() {
        mAdapter = ChargeAdapter(mContext)
        mAdapter?.setDecorator { holder, _, _ ->
            val itemBinding: ItemChargeBinding = holder.binding as ItemChargeBinding
            itemBinding.root.setOnClickListener {
                selectProduct(holder.adapterPosition)
            }
        }
        mBinding.rv.adapter = mAdapter

        mLayoutManager = GridLayoutManager(mContext, 3)
        mBinding.rv.layoutManager = mLayoutManager

        
        val list = ArrayList<ProductModel>()
        ProductModel(1, 1, 100).apply { list.add(this) }
        ProductModel(2, 6, 600).apply { list.add(this) }
        ProductModel(3, 18, 1800).apply { list.add(this) }
        ProductModel(4, 30, 3000).apply { list.add(this) }
        ProductModel(5, 50, 5000).apply { list.add(this) }
        ProductModel(6, 98, 9800).apply { list.add(this) }

        mAdapter?.addAll(list)
    }

    private fun selectProduct(index: Int) {
        mAdapter?.selectProduct(index)

        mBinding.tvCharge.text = "确认支付 ${mAdapter?.getData()?.get(index)?.getSignAndYuan()}"
    }

    override fun createHandler() {
        mBinding.nbv.setOnBackListener {
            onBackPressed()
        }
        mBinding.nbv.setOnMenuClickListener {
            ChargeListActivity.openActivity(mContext)
        }
        mBinding.tvCharge.setOnClickListener {
            
            popUpChargeDialog(mAdapter?.getCurrentProduct()!!)
        }
        mBinding.tvCommonProblem.setOnClickListener {
            WebViewActivity.openChargeProtocolActivity(mContext)
        }
    }

    override fun loadData(savedInstanceState: Bundle?) {
        mViewModel?.balanceOutcome?.observe(this, Observer<Outcome<GetBalanceRes>> { t ->
            when (t) {
                is Outcome.Success -> {
                    mBinding.tvBalance.text = StringUtil.format("{0,number,0.00}", t.data.balance / 100f)
                }
                is Outcome.Failure -> {
                    DialogUtil.showError(mContext, t.e)
                }
                is Outcome.Progress -> {
                    if (t.loading) {
                        
                    } else {

                    }
                }
            }
        })

        mViewModel?.loadBalance()
    }

    private fun popUpChargeDialog(productModel: ProductModel) {
        val bottomSheetDialog = BottomSheetDialog(mContext, R.style.CustomBottomSheetDialogTheme)
        bottomSheetDialog.setContentView(R.layout.dialog_charge)
        val wechat = bottomSheetDialog.findViewById<View>(R.id.wechat)
        val alipay = bottomSheetDialog.findViewById<View>(R.id.alipay)
        val cancel = bottomSheetDialog.findViewById<View>(R.id.cancel)

        
        wechat?.setOnClickListener {
            val payReq = PayReq()
            payReq.payway = PayMethod.WEIXIN
            payReq.product_id = productModel.productId

            HttpMethods.getPayService().pay(payReq)
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object : HttpSubscriber<PayResult>() {
                        override fun onSuccess(response: PayResult?) {
                            val weixinPayReq = com.tencent.mm.opensdk.modelpay.PayReq()
                            weixinPayReq.appId = BuildConfig.WECHAT_APP_ID
                            weixinPayReq.partnerId = response?.partnerid
                            weixinPayReq.prepayId = response?.prepayid
                            weixinPayReq.packageValue = response?.packageX
                            weixinPayReq.nonceStr = response?.noncestr
                            weixinPayReq.timeStamp = response?.timestamp
                            weixinPayReq.sign = response?.sign

                            val uniPay = UniPay.Builder(this@ChargeActivity)
                                    .method(UniPayMethod.wechatPay)
                                    .onListener(object : UniPayListener {
                                        override fun onSuccess() {
                                            mViewModel?.loadBalance()
                                            ToastUtil.showShort("支付成功")
                                            bottomSheetDialog.dismiss()
                                        }

                                        override fun onError(errorMsg: String) {
                                            ToastUtil.showShort("尚未支付成功，请重新支付")
                                        }
                                    })
                                    .build()
                            if (!uniPay.isAppInstalled) {
                                ToastUtil.showShort("没有安装微信")
                                return
                            }
                            uniPay.pay(weixinPayReq)
                        }

                        override fun onFailure(errMsg: String?, response: PayResult?, code: Int) {
                            DialogUtil.showError(this@ChargeActivity, errMsg)
                        }

                    })
        }
        alipay?.setOnClickListener {
            val payReq = PayReq()
            payReq.payway = PayMethod.ALI
            payReq.product_id = productModel.productId

            HttpMethods.getPayService().pay(payReq)
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object : HttpSubscriber<PayResult>() {
                        override fun onSuccess(response: PayResult?) {
                            LogUtil.d("alipay results: ${response?.ali_result}")

                            val unipay = UniPay.Builder(this@ChargeActivity)
                                    .method(UniPayMethod.alipay)
                                    .onListener(object : UniPayListener {
                                        override fun onSuccess() {
                                            mViewModel?.loadBalance()
                                            ToastUtil.showShort("支付成功")
                                            bottomSheetDialog.dismiss()
                                        }

                                        override fun onError(errorMsg: String) {
                                            ToastUtil.showShort("尚未支付成功，请重新支付")
                                        }

                                    })
                                    .build()
                            unipay.pay(response?.ali_result)
                        }

                        override fun onFailure(errMsg: String?, response: PayResult?, code: Int) {
                            DialogUtil.showError(this@ChargeActivity, errMsg)
                        }

                    })
        }

        cancel?.setOnClickListener { bottomSheetDialog.dismiss() }
        bottomSheetDialog.show()
    }

}